//
//  BJNetManager.m
//  
//
//  Created by  on 2023/3/3.
//

#import "BJNetManager.h"

@interface BJNetManager ()

@property (nonatomic) NSString *userToken;
@property (nonatomic) NSInteger page;
@end

@implementation BJNetManager

+ (instancetype)shareNetManager{
    static BJNetManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [BJNetManager new];
    });
    return manager;
}

////获取商品列表
- (id)postSearchGoodsWithcompletionHandler:(void (^)(BJGoodsSearchModel *model, NSError *))completionHandler{
    NSDictionary *param = @{
        @"isIncludeSubscription":@(NO),
        @"payChannel":@"IAP",
    };
    return [self POST:kPath_searchgoods parameters:param completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        BJGoodsSearchModel *model = [BJGoodsSearchModel parse:responseObj];
        !completionHandler ?: completionHandler(model, error);
    }];
}

//创建充值订单接口 POST
- (id)postCreateRechargeGoodsCode:(NSString *)goodsCode completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    NSDictionary *param = @{
        @"goodsCode":goodsCode,
        @"payChannel":@"IAP",
    };
    return [self POST:kPath_createRecharge_a parameters:param completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        !completionHandler ?: completionHandler(responseObj, error);
    }];
}
////
////支付成功后验证凭据
- (id)postPaymentWithOrderNo:(NSString *)orderNo payload:(NSString *)payload transactionId:(NSString *)transactionId completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    NSDictionary *param = @{
        @"orderNo":orderNo ? orderNo:@"",                ///支付订单号 ,创建订单返回的订单号
        @"payload":payload ? payload:@"",                ///支付有效载荷 ,苹果返回的购买凭证
        @"transactionId":transactionId ? transactionId:@"",    ///内购交易号 苹果返回的交易流水号
        @"type":@(1)    ///苹果默认1
    };
    return [self POST:kPath_paymentIpa_a parameters:param completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        !completionHandler ?: completionHandler(responseObj, error);
    }];
}


/**
 删除账号
 */
- (id)postDeleteAccountWithCompletionHandler:(void(^)(id _Nonnull,NSError *error))completionHandler{
    return [self POST:kPath_deleteAccount parameters:@{} completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        NSDictionary *dict = responseObj;
        NSInteger code = [dict[@"code"] integerValue];
        if (!error && code == 0){
            [[BJUserManager sharedManager] setUserToken:@""];
            [[BJUserManager sharedManager] setUseId:@""];
        }
        !completionHandler ?: completionHandler(responseObj, error);
    }];
}

//=========================
/**
 登录
 */
- (id)postLoginWithOauthType:(int)oauthType token:(NSString *)token completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    NSDictionary *parameters = @{
        @"oauthType":@(oauthType),
        @"token":token
    };
    
    return [self POSTForLogin:kPath_login parameters:parameters completionHandler:^(id responseObj, NSError *error) {
        BJLoginOauthModel *model = [BJLoginOauthModel parse:responseObj];
        [[BJUserManager sharedManager] setUserToken:model.data.token];
        [[BJUserManager sharedManager] setUseId:model.data.userInfo.userId];
        !completionHandler ?: completionHandler(responseObj, error);
    }];
}

/**
 获取策略
 */
- (id)getGetStrategyWithCompletionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    return [self GET:kPath_getStrategy parameters:@{} completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        BJGetStrategyModel *model = [BJGetStrategyModel parse:responseObj];
        [BJConfigManager sharedManager].configModel = model;
        !completionHandler ?: completionHandler(responseObj, error);
    }];
}

///**
// 获取主播墙列表
// */
- (id)postSearchAnchorWallWithParm:(NSDictionary *)parm completionHandler:(void (^)(BJAnchorWallModel * , NSError * ))completionHandler{
    return [self POST:kPath_searchWall parameters:parm completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        BJAnchorWallModel *model = [BJAnchorWallModel parse:responseObj];
        !completionHandler ?: completionHandler(model, error);
    }];
}

/**
 校验token
 */
- (id)postIsValidTokenWithCompletionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    NSDictionary *parm = @{
        @"token":[[BJUserManager sharedManager] getUserToken]
    };
    return [self POST:kPath_isValidToken parameters:parm completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {


        !completionHandler ?: completionHandler(responseObj, error);
    }];
}

//关注主播
- (id)postAddFriendWithFollowUserId:(NSInteger)userId completionHandler:(void (^)(id  _Nonnull responseObj,NSError * _Nonnull))completionHandler
{
    NSDictionary *parm = @{
        @"followUserId":@(userId)
    };
    return [self POST:kPath_AddFriend parameters:parm completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        !completionHandler ?:completionHandler(responseObj,error);
    }];
}
////取关
- (id)postDeleteFriendWithFollowUserId:(NSString *)userId completionHandler:(void (^)(id  _Nonnull responseObj,NSError * _Nonnull))completionHandler
{
    NSDictionary *parm = @{
        @"followUserId":userId
    };
    return [self POST:kPath_unfriend parameters:parm completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        !completionHandler ?:completionHandler(responseObj, error);
    }];
}

- (id)postGetFriendListPageWithlimit:(int)limit completionHandler:(void (^)(BJFollowedUserModel * _Nonnull, NSError * _Nonnull))completionHandler{

    NSDictionary *parm = @{
        @"limit":@(limit),
        @"page":@(1)
    };
    return [self POST:kPath_getFriendList parameters:parm completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        BJFollowedUserModel *model = [BJFollowedUserModel parse:responseObj];
        !completionHandler ?: completionHandler(model,error);

    }];
}


- (id)getGetUserInfoWithUserId:(NSString *)userId completionHandler:(void (^)(BJGetUserInfoModel * _Nonnull, NSError * _Nonnull))completionHandler{
    NSString *path = [NSString stringWithFormat:@"%@?userId=%@",kPath_getUserInfo,userId];
    return [self GET:path parameters:@{} completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        BJGetUserInfoModel *model = [BJGetUserInfoModel parse:responseObj];
        !completionHandler ?: completionHandler(model, error);
    }];
}

//保存用户信息
- (id)postSaveUserInfoWithParam:(NSDictionary *)param completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    return [self POST:kPath_saveUserInfo parameters:param completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        !completionHandler ?: completionHandler(responseObj, error);
    }];
}

//获取当前用户金币
- (id)getUserCurrentCoinsWithcompletionHandler:(void (^)(BJUserCoinsModel * _Nonnull, NSError * _Nonnull))completionHandler{
    NSString *path = [NSString stringWithFormat:@"%@",kPath_getUserCoins];
    return [self GET:path parameters:@{} completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        BJUserCoinsModel *model = [BJUserCoinsModel parse:responseObj];
        !completionHandler ?:completionHandler(model,error);
    }];
}

////拉黑列表
- (id)getBlockListWithCompletionHandler:(void (^)(BJBlockListModel * _Nonnull, NSError * _Nonnull))completionHandler{
    return [self POST:kPath_blockList parameters:@{} completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        BJBlockListModel *model = [BJBlockListModel parse:responseObj];
        !completionHandler ?:completionHandler(model,error);
    }];
}

//获取Oss服务器的信息
- (id)getOssPolicyWithcompletionHandler:(void (^)(BJOssPolicModel * _Nonnull, NSError * _Nonnull))completionHandler{
    return [self GET:kPath_policy parameters:@{} completionHandler:^(id  responseObj, NSError * error) {
        BJOssPolicModel *model = [BJOssPolicModel parse:responseObj];
        !completionHandler ?: completionHandler(model, error);
    }];
}


////上传图片到Oss服务器
- (id)postUploadImageToOssWithImage:(UIImage *)image completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    
    NSString *path = [BJConfigManager sharedManager].ossPolicModel.host;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *file = [NSString stringWithFormat:@"%@.jpg",str];
    NSData *imagedata = UIImageJPEGRepresentation(image, 0.5f);
    NSDictionary *params = @{
        @"ossaccessKeyId" : [BJConfigManager sharedManager].ossPolicModel.accessKeyId,
        @"policy"         : [BJConfigManager sharedManager].ossPolicModel.policy,
        @"signature"      : [BJConfigManager sharedManager].ossPolicModel.signature,
        @"callback"       : [BJConfigManager sharedManager].ossPolicModel.callback,
        @"key"            : [NSString stringWithFormat:@"%@%@",[BJConfigManager sharedManager].ossPolicModel.dir,file],
    };
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imagedata name:@"file" fileName:file mimeType:@"image/jpeg"];
    } error:nil];
    
    NSDictionary *dict = [[BJConfigManager sharedManager]getDefHeaders];
    request.allHTTPHeaderFields = dict;
    [request setValue:[NSString stringWithFormat:@"Bearer%@",[[BJUserManager sharedManager]getUserToken]] forHTTPHeaderField:@"Authorization"];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        //进度
    } completionHandler:^(NSURLResponse *_Nonnull response,id _Nonnull responseObject, NSError * _Nullable error){
        !completionHandler ?:completionHandler(responseObject, error);
    }];
    [uploadTask resume];
    
    return 0;
}


- (id)postUpdateAvatarWithAvatarPath:(NSString *)avatarPath completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    NSDictionary *param = @{
        @"avatarPath":avatarPath,
    };
    return [self POST:kPath_updateAvatar parameters:param completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        !completionHandler ?:completionHandler(responseObj, error);
    }];
}

- (id)postSecurityLogoutWithCompletionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    return [self POST:kPath_logout parameters:@{} completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        [[BJUserManager sharedManager] setUserToken:@""];
        [[BJUserManager sharedManager] setUseId:@""];
        !completionHandler ?:completionHandler(responseObj,error);
    }];
}

//拉黑举报
- (id)postBlockReportWithParam:(NSMutableDictionary *)parm completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    return [self POST:kPath_complain parameters:parm completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        !completionHandler ?:completionHandler(responseObj, error);
    }];
}
//
//取消拉黑
- (id)postRemoveBlockWithBlockUserId:(NSInteger)userId completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    NSDictionary *param = @{
        @"blockUserId" : @(userId)
    };
    return [self POST:kPath_removeBlock parameters:param completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        !completionHandler ?:completionHandler(responseObj, error);
    }];
}

//日志打点上报
- (id)postLogWithParam:(NSArray *)dataArray{
    
    NSString *userId = [[BJUserManager sharedManager] getUserId].length>0?[[BJUserManager sharedManager] getUserId]:@"";

    // 获取当前应用的主bundle
    NSBundle *mainBundle = [NSBundle mainBundle];
    // 获取bundle的标识符，通常是包名
    NSString *bundleIdentifier = [mainBundle bundleIdentifier];

    NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
    NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];
    NSString *languageCode = [languageDic objectForKey:@"kCFLocaleLanguageCodeKey"];
    NSDictionary *dict = @{
        @"data":dataArray, //data 上报 日志数据数组
        @"log_type":@"event", //日志属性
        @"subtype":@"global_behavior", //日志类型
        @"behavior":@"event", //日志属性
        @"device-id":[UUIDStrengthen getDeviceIDInKeychain], //设备id
        @"user_id":userId, // 用户id
        @"pkg":bundleIdentifier, //包名
        @"ver":kCurVersion, //版本号
        @"p_ver":kCurBuild,
        @"platform":@"iOS", //android or ios
        @"model":[[UIDevice currentDevice] model], //手机型号
        @"lan_id":self.launcherId,//客户端启动唯一标识，用于区分是否是同一次启动
        @"sec_id": @(self.serialId++), //日志次数 日递增
        @"sys_lan":languageCode, //手机系统语言
        @"country":@"USA", //用户国家
        @"bizver":@"",
        @"tm":@([self gs_getCurrentTimeToMilliSecond]) //当前时间戳
    };
    NSLog(@"%@",dict);
    
    return [self POST:k_logLiveChatPath parameters:@[dict] completionHandler:^(id  responseObj, NSError *  error) {
        
    }];
                
}

- (long long)gs_getCurrentTimeToMilliSecond {
    
    double currentTime = [[NSDate date] timeIntervalSince1970] * 1000;
    
    long long iTime = (long long)currentTime;
    
    return iTime;
    
}

- (id)postReviewModeConsumeWithOutlay:(NSInteger)outlay source:(NSString *)source completionHandler:(void (^)(id _Nonnull, NSError * _Nonnull))completionHandler{
    NSDictionary *param = @{
        @"outlay":@(outlay),
        @"source":source,
    };
    return [self POST:kPath_reviewModeConsume_a parameters:param completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        !completionHandler ?: completionHandler(responseObj, error);
    }];
}

- (id)getShortLinkMediaSearchWithCompletionHandler:(void(^)(BJVodeoListModel *model, NSError *error))completionHandler{
    
    NSArray *parm = @[@{@"mediaPath":@"BowJoyV/video/1.mp4",
                        @"mediaType":@"video"},
                      @{@"mediaPath":@"BowJoyV/video/2.mp4",
                                          @"mediaType":@"video"},
                      @{@"mediaPath":@"BowJoyV/video/3.mp4",
                                          @"mediaType":@"video"},
                      @{@"mediaPath":@"BowJoyV/video/4.mp4",
                                          @"mediaType":@"video"},
                      @{@"mediaPath":@"BowJoyV/video/5.mp4",
                                          @"mediaType":@"video"},
                      @{@"mediaPath":@"BowJoyV/video/6.mp4",
                                          @"mediaType":@"video"},
                      @{@"mediaPath":@"BowJoyV/video/7.mp4",
                                          @"mediaType":@"video"},
                      @{@"mediaPath":@"BowJoyV/video/8.mp4",
                                          @"mediaType":@"video"},
                      @{@"mediaPath":@"BowJoyV/video/9.mp4",
                                          @"mediaType":@"video"},
                      @{@"mediaPath":@"BowJoyV/video/10.mp4",
                                          @"mediaType":@"video"},
    ];
    return [self POST:kPath_shortLink_media_search parameters:parm completionHandler:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
        BJVodeoListModel *model = [BJVodeoListModel parse:responseObj];
        !completionHandler ?:completionHandler(model,error);
    }];
}
@end
